package club.hicode.daydayup.controller;

import cn.hutool.json.JSONUtil;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * @author Liu Chunfu
 * @date 2018-07-11 上午11:36
 **/
//@WebListener
public class MicWebListener implements ServletRequestListener {


    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        WebThreadLocal.threadLocal.remove();
    }

    @Override
    public void requestInitialized(ServletRequestEvent requestEvent) {
        System.out.println("requestInitialized.....");
        if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
            throw new IllegalArgumentException("Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
        } else {
            HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
            MAPIHttpServletRequestWrapper multiReadRequest = null;
            try {
                multiReadRequest = new MAPIHttpServletRequestWrapper(request);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                BufferedReader reader = multiReadRequest.getReader();
                String s = reader.readLine();
                if (s == null) {
                    WebThreadLocal.threadLocal.set(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //Map<String, String[]> parameterMap = request.getParameterMap();
            //System.out.println(JSONUtil.toJsonStr(parameterMap));
            //
        }
    }
}
